package com.qiyadeng.wechat.web;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.qiyadeng.company.biz.MmtService;
import com.qiyadeng.company.biz.RandomUtils;
import com.qiyadeng.company.biz.ResSelectUser;
import com.qiyadeng.company.biz.RespGrantTicket;
import com.qiyadeng.company.biz.TicketGrant;
import com.qiyadeng.wechat.config.WeChatConstant;
import com.qiyadeng.wechat.roo.model.LocalUser;
import com.qiyadeng.wechat.roo.model.SmsRecord;
import com.qiyadeng.wechat.roo.model.UserBinding;

@Controller
public class AccountController {

	Logger logger = LoggerFactory.getLogger(AccountController.class);
	
	@RequestMapping(value="/acct/sendCheckCode")
	@ResponseBody
	public String sendCheckCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String phone = ServletRequestUtils.getStringParameter(request, "phone");
		logger.debug("get phone number"+ phone);
		String randomCode = RandomUtils.genSixRandomCode();
		Long count = SmsRecord.getCountSms(phone);
		if(count>WeChatConstant.SMS_MAX_COUNT){
			return "failure:短信发送次数过多";
		}
		else {
			MmtService mmt = new MmtService("sms");
			mmt.sendSms(phone, WeChatConstant.SMS_CHECK_CODE + randomCode);
			SmsRecord.saveSms(phone, randomCode);//保存校验码
			return "success";
		}
	}
	
	//新用户注册到本地
	@RequestMapping(value="/acct/register")
	public String registerUser(Model model,HttpServletRequest request, HttpServletResponse response) throws Exception{
		String phone = ServletRequestUtils.getStringParameter(request, "phone");
		String name = ServletRequestUtils.getStringParameter(request, "name");
		String checkCode = ServletRequestUtils.getStringParameter(request, "code");
		String email = ServletRequestUtils.getStringParameter(request, "email");
		String idNo = ServletRequestUtils.getStringParameter(request, "idNo");
		String wechatuser = ServletRequestUtils.getStringParameter(request, "wechatuser");
		Joiner joiner = Joiner.on(";").skipNulls();
		String log = joiner.join("phone:",phone,"name:",name,"checkCode:",checkCode,"email:",email,"idNo:",idNo,"wechatuser:",wechatuser);
		logger.debug("request parameter:"+log);
		
		// 检查checkcode是否正确
		SmsRecord smsRecord = SmsRecord.getLastestSmsByPhone(phone);
		if(smsRecord != null && smsRecord.getContent().equalsIgnoreCase(checkCode)){
			//校验码正确
			LocalUser.saveLocalUser(name, idNo, phone, email, wechatuser);
		}
		else {
			//校验码错误
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "校验码错误");
			return "wechat/message";
		}
		
		//注册
		MmtService mmt = new MmtService();
		mmt.addUserInfo(name, "0", idNo, phone, email);//0 is 身份证
		//add 2013-10-28
		MmtService sms = new MmtService("");
		RespGrantTicket ticket = mmt.grantTicket(phone);
		if(ticket != null){
			TicketGrant tg= ticket.getTickets().get(0);
			if(tg != null){
				//String smsStr = String.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketName(),tg.getTicketNo());
				String smsStr =  MessageFormat.format(WeChatConstant.REG_MSG, tg.getTicketNo());
				sms.sendSms(wechatuser, smsStr);
				model.addAttribute("code","成功");
				model.addAttribute("reason",smsStr);
			}
			else {
				model.addAttribute("code","失败");
				model.addAttribute("reason","发券失败。");
			}			
		}
		
		model.addAttribute("code", "成功");
		return "wechat/message";
	}
	
	@RequestMapping(value="/acct/modify")
	public String modifyPassword(Model model,HttpServletRequest request, HttpServletResponse response){
		MmtService  mmt = new MmtService();
		String cardNo = request.getParameter("cardNo");
		String password = request.getParameter("password");
		String newPassword = request.getParameter("newPassword");
		String newPasswordAg = request.getParameter("newPasswordAg");
		String message = mmt.modifyPassword(cardNo, password, newPassword, newPasswordAg, "1");
		if(Strings.isNullOrEmpty(message)){
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "修改卡密码失败。");
		}
		else {
			model.addAttribute("code", "成功");
			model.addAttribute("reason", message);
		}
		
		return "wechat/message";
	}
	
	//绑卡,代码和acct/bind基本一致
	@RequestMapping(value="/acct/bindcard")
	public String bindCard(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String phone = ServletRequestUtils.getStringParameter(request, "phone");
		String checkCode = ServletRequestUtils.getStringParameter(request, "code");
		Joiner joiner = Joiner.on(";").skipNulls();
		String wechatuser = ServletRequestUtils.getStringParameter(request, "wechatuser");
		String log = joiner.join("phone:",phone,"checkCode:",checkCode,"wechatuser",wechatuser);
		logger.debug("binduser request parameter:"+log);

		MmtService sms = new MmtService("");
		MmtService mmt = new MmtService();
//		RespGrantTicket ticket = mmt.grantTicket(phone);
//		TicketGrant tg= ticket.getTickets().get(0);
//		sms.sendSms(phone, "恭喜您获得优惠券:"+tg.getTicketName()+","+tg.getTicketNo());

		// 检查checkcode是否正确
		SmsRecord smsRecord = SmsRecord.getLastestSmsByPhone(phone);
		if(smsRecord != null && smsRecord.getContent().equalsIgnoreCase(checkCode)){
			
			//校验码正确
			/*
			MmtService mmt = new MmtService();
			ResSelectUser user  = mmt.selectUserInfo(null, null, phone, null);
			if(user != null){
				UserBinding.saveUserBinding(wechatuser, phone);
			}
			else {
				model.addAttribute("code", "失败");
				model.addAttribute("reason", "你的手机号码未注册成为会员");
				return "wechat/message"; 
			}
			*/
		}
		else {
			//校验码错误
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "校验码错误");
			return "wechat/message";
		}
		
		//检查用户是否是会员
		ResSelectUser user = null;
		try {
			user = mmt.selectUserInfo(null, null, phone, null);//TODO手机号码 查询有多个用户
		} catch (Exception e) {
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "您的手机号码存在多个用户。");
			logger.warn("查询用户时出错"+e.getMessage());
			e.printStackTrace();
		}
		//绑定
		if(user != null){
			UserBinding.saveUserBinding(wechatuser, phone);
			LocalUser.updateLocalUserCard(phone, user.getInformation().getCardlist().get(0).getCardno());
			RespGrantTicket ticket = mmt.grantTicket(phone);
			if(ticket != null){
				TicketGrant tg= ticket.getTickets().get(0);
				if(tg != null){
					//String smsStr = String.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketName(),tg.getTicketNo());
					String smsStr =  MessageFormat.format(WeChatConstant.REG_MSG, tg.getTicketNo());
					sms.sendSms(wechatuser, smsStr);
					model.addAttribute("code","成功");
					model.addAttribute("reason",smsStr);
				}
				else {
					model.addAttribute("code","失败");
					model.addAttribute("reason","发券失败。");
				}			
			}
			model.addAttribute("code", "成功");
			model.addAttribute("reason", "绑定用户成功");
		}
		return "wechat/message";
	}
	
	@RequestMapping(value="/acct/bind")
	public String bindUser(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String phone = ServletRequestUtils.getStringParameter(request, "phone");
		String checkCode = ServletRequestUtils.getStringParameter(request, "code");
		Joiner joiner = Joiner.on(";").skipNulls();
		String wechatuser = ServletRequestUtils.getStringParameter(request, "wechatuser");
		String log = joiner.join("phone:",phone,"checkCode:",checkCode,"wechatuser",wechatuser);
		logger.debug("binduser request parameter:"+log);
		
		MmtService sms = new MmtService("");
		MmtService mmt = new MmtService();
//		RespGrantTicket ticket = mmt.grantTicket(phone);
//		TicketGrant tg= ticket.getTickets().get(0);
//		sms.sendSms(phone, "恭喜您获得优惠券:"+tg.getTicketName()+","+tg.getTicketNo());

		
		// 检查checkcode是否正确
		SmsRecord smsRecord = SmsRecord.getLastestSmsByPhone(phone);
		if(smsRecord != null && smsRecord.getContent().equalsIgnoreCase(checkCode)){
			//校验码正确
			/*
			MmtService mmt = new MmtService();
			ResSelectUser user  = mmt.selectUserInfo(null, null, phone, null);
			if(user != null){
				UserBinding.saveUserBinding(wechatuser, phone);
			}
			else {
				model.addAttribute("code", "失败");
				model.addAttribute("reason", "你的手机号码未注册成为会员");
				return "wechat/message"; 
			}
			*/
		}
		else {
			//校验码错误
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "校验码错误");
			return "wechat/message";
		}
		
		//检查用户是否是会员
		ResSelectUser user = null;
		try {
			user = mmt.selectUserInfo(null, null, phone, null);//TODO手机号码 查询有多个用户
		} catch (Exception e) {
			model.addAttribute("code", "失败");
			model.addAttribute("reason", "您的手机号码 不存在活是存在多个用户。");
			logger.warn("查询用户时出错"+e.getMessage());
			e.printStackTrace();
		}
		//绑定
		if(user != null){
			UserBinding.saveUserBinding(wechatuser, phone);
			LocalUser.updateLocalUserCard(phone, user.getInformation().getCardlist().get(0).getCardno());//更新本地关系
			RespGrantTicket ticket = mmt.grantTicket(phone);
			if(ticket != null){
				TicketGrant tg= ticket.getTickets().get(0);
				if(tg != null){
					//String smsStr = String.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketName(),tg.getTicketNo());
					String smsStr =  MessageFormat.format(WeChatConstant.REG_MSG, tg.getTicketNo());
					sms.sendSms(wechatuser, smsStr);
					model.addAttribute("code","成功");
					model.addAttribute("reason",smsStr);
				}
				else {
					model.addAttribute("code","失败");
					model.addAttribute("reason","发券失败。");
				}			
			}
			model.addAttribute("code", "成功");
			model.addAttribute("reason", "绑定用户成功");
		}
		
		return "wechat/message";
	}
}
